package net.maku.kyy.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class FileUploadUtil {

    @Value("${file.upload.dir:/upload/dir}")
    private String uploadDir;

    private final Object lock = new Object();

    public List<String> uploadFiles(List<MultipartFile> files, String imgname) throws IOException {
        List<String> imgUrls = new ArrayList<>();
        if (files == null || files.isEmpty()) return imgUrls;

        // 获取绝对路径
        String absolutePath = System.getProperty("user.dir") + uploadDir;
        File dir = new File(absolutePath);
        System.out.println(absolutePath);
        synchronized (lock) { // 确保同一时间只有一个线程执行目录创建
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    throw new IOException("无法创建上传目录: " + absolutePath);
                }
            }
        }
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String fileName = imgname+UUID.randomUUID() +
                        "." + getFileExtension(file.getOriginalFilename());
                String filePath = absolutePath + fileName;

                file.transferTo(new File(filePath));

                // 生成可访问的URL
                String imgUrl = "https://yourdomain.com/upload/" + fileName;
                imgUrls.add(imgUrl);
            }
        }
        return imgUrls;
    }

    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
